package com.nnnu.orange.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nnnu.orange.constant.MessageConstants;
import com.nnnu.orange.constant.StatusConstants;
import com.nnnu.orange.exception.ObjectException;
import com.nnnu.orange.pojo.dto.PaymentQueryDto;
import com.nnnu.orange.pojo.entity.Payments;
import com.nnnu.orange.mapper.PaymentsMapper;
import com.nnnu.orange.pojo.vo.PaymentVO;
import com.nnnu.orange.result.PageResult;
import com.nnnu.orange.service.IPaymentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nnnu.orange.utils.ThreadLocalUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 支付记录表，记录用户支付的罚款信息 服务实现类
 * </p>
 *
 * @author zk
 * @since 2024-12-08
 */
@Service
public class PaymentsServiceImpl extends ServiceImpl<PaymentsMapper, Payments> implements IPaymentsService {

    /**
     * 用户支付逾期订单
     *
     * @param orderId 订单ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payFine(Integer orderId) {
        Long userId = ThreadLocalUtil.getId();
        Payments payment = baseMapper.selectOne(new LambdaQueryWrapper<Payments>()
                .eq(Payments::getId, orderId)
                .eq(Payments::getUserId, userId));
        if (payment == null) {
            throw new ObjectException(MessageConstants.PAY_NULL);
        }
        if (baseMapper.updateById(payment.setStatus(StatusConstants.ONE).setPaidDate(LocalDateTime.now())) < 1) {
            throw new ObjectException(MessageConstants.PAY_ERR);
        }
    }

    /**
     * 分页查询所有订单列表
     *
     * @param queryDto dto
     * @return 分页后的数据
     */
    @Override
    public PageResult<?> pageList(@NotNull PaymentQueryDto queryDto) {
        Integer status = queryDto.getStatus();
        LocalDate paidDate = queryDto.getPaidDate();
        LocalDateTime start = paidDate != null ? paidDate.atStartOfDay() : null;
        LocalDateTime end = paidDate != null ? paidDate.atTime(LocalTime.MAX) : null;
        Page<Payments> paymentsPage = baseMapper.selectPage(
                new Page<>(queryDto.getPageNum(), queryDto.getPageSize()),
                new LambdaQueryWrapper<Payments>()
                        .eq(status != null, Payments::getStatus, status)
                        .ge(end != null, Payments::getPaidDate, end)
                        .le(start != null, Payments::getPaidDate, start));
        return new PageResult<>(paymentsPage.getTotal(), paymentsPage.getRecords());
    }

    /**
     * 获取订单详细信息
     *
     * @param id 订单ID
     * @return 订单实体
     */
    @Override
    public PaymentVO detail(Integer id) {
        return baseMapper.selectOneById(id);
    }

    /**
     * 批量删除订单信息
     *
     * @param ids id列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(@NotNull List<Integer> ids) {
        if (CollectionUtil.isNotEmpty(ids)) {

            List<Integer> list = ids.stream().distinct().toList();


            List<Payments> payments = baseMapper.selectBatchIds(list);
            if (CollectionUtil.isEmpty(payments)) {
                throw new ObjectException(MessageConstants.LIST_NULL);
            }

            boolean s = payments.stream()
                    .anyMatch(payment -> !Objects.equals(payment.getStatus(), StatusConstants.ONE));
            if (s) {
                throw new ObjectException("存在未支付的订单，无法删除！");
            }
            baseMapper.deleteBatchIds(list);
        } else {
            throw new ObjectException(MessageConstants.LIST_NULL);
        }
    }
}
